package com.ficus.road.maintain.third.zh.score;

import com.alibaba.fastjson.JSONArray;
import com.ficus.road.maintain.core.model.Unit;
import com.ficus.road.maintain.core.model.zh.UnitScoreDetail;
import com.ficus.road.maintain.core.model.zh.UnitScoreDetailZH;
import com.ficus.road.maintain.dao.UnitDao;
import com.ficus.road.maintain.dao.UnitScoreDetailDao;
import com.ficus.road.maintain.third.zh.BaseZH;
import com.ficus.road.maintain.util.MyDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiawen yang
 * @date 2022/8/20 下午3:05
 */
@Component
@Slf4j
public class ZHUnitScoreDetail extends BaseZH {
    @Autowired
    private UnitScoreDetailDao unitScoreDetailDao;
    @Autowired
    private UnitDao unitDao;

    @PostConstruct
    void init() {
        arg0 = "ytkjQueryScore";
        errMsg = "调用中海接口获取标段扣分详情异常!";
        successMsg = "调用中海接口获取标段扣分详情成功!";
    }

    @Scheduled(cron = "0 0 14 * * ?", zone = "GMT+8:00")
//    @Scheduled(cron = "0/5 * * * * ?", zone = "GMT+8:00")
    public void refreshUnitScoreDetail() {
        init();
        String yearMonth = MyDateUtil.dateFormatStr(MyDateUtil.getFirstDayOfLastMonth(), "yyyy-MM");
        List<Unit> unitList = unitDao.findAll();
        unitList.forEach(unit -> {
            arg1 = "{\"sections\":\"" + unit.getId() + "\",\"yearMonth\":\"" + yearMonth + "\"}";
            String zhData = getZHData();
            if (StringUtils.isEmpty(zhData)) {
                return;
            }
            List<UnitScoreDetailZH> unitScoreDetailZhList = JSONArray.parseArray(zhData, UnitScoreDetailZH.class);
            List<UnitScoreDetail> unitScoreDetails = unitScoreDetailZhList.stream().map(item -> item.convert2UnitScoreDetail(item, yearMonth)).collect(Collectors.toList());
            unitScoreDetails.forEach(unitScoreDetailDao::saveOrUpdate);
        });
        log.info("score detail end");
    }
}
